package handler

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"honghu_be/common"
	"honghu_be/dal"
	"honghu_be/model"
	"honghu_be/model/vo"
)

func GetArticle(c *gin.Context) {
	req := &model.GetArticleRequest{}
	if err := c.ShouldBindUri(req); err != nil {
		c.JSON(400, err.Error())
		return
	}
	resp, err := getArticle(c, req.ArticleId)
	if err != nil {
		common.WriteError(c, err)
		return
	}
	c.JSON(200, resp)
}

func getArticle(c *gin.Context, articleId string) (*model.GetArticleResponse, error) {
	pos, err := dal.GetArticles(c, &dal.GetArticlesRequest{
		ArticleId: cast.ToInt(articleId),
	})
	if err != nil {
		return nil, err
	}
	if len(pos) == 0 {
		return nil, errors.New(fmt.Sprintf("article_%d not found", articleId))
	}
	return &model.GetArticleResponse{
		Meta:    common.MetaOk,
		Article: vo.ToArticleVo(pos[0]),
	}, nil
}
